package com.guet.careapp.controller.rest.controller.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guet.careapp.controller.rest.common.errorCode.Error;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCode;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCodeFactory;
import com.guet.careapp.pojo.TUserGuardianInfo;
import com.guet.careapp.pojo.TUserInfo;
import com.guet.careapp.pojo.TUserRelation;
import com.guet.careapp.pojo.TUserUnderGuardiansInfo;
import com.guet.careapp.pojo.rest.AjaxReturn;
import com.guet.careapp.pojo.rest.Introduction;
import com.guet.careapp.service.*;
import com.guet.careapp.utils.ConvertUtils;
import com.guet.careapp.utils.TimeHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.*;

@Controller
@Path("/services/transmission")
public class NormalServicesController {

    protected static final org.slf4j.Logger LOG = LoggerFactory.getLogger(NormalServicesController.class);

    @Autowired
    private IInstructionService instructionService;

    @Autowired
    private IUserGuardianInfoService guardianInfoService;

    @Autowired
    private IUserRelationService relationService;

    @Autowired
    private IUserUnderGuardiansInfoService underGuardiansInfoService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IPushService pushService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private ISMSService smsService;


    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @POST
    @Path("/tumble")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String notifyTumble(String json) {
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        String uid = "" + map.get("bgid");
        if (uid.equals("null"))
            return gsonStr(Error.NotFond);
        //查找这个人的监护人是谁，可能有100个那么多
        List<TUserRelation> relations = relationService.queryByHql("SELECT t FROM TUserRelation t WHERE t.ugInfoId = " + uid + "");
        List<String> users = new ArrayList<>();
        for (TUserRelation r : relations) {
            users.add(r.getGInfoId().getTUserInfo().getDeviceId());
        }
        //调用推送服务，发送这个推到信息
        Error error = pushService.PushTumble(users, relations.get(0).getUgInfoId().getTUserInfo().getName());
        //发送短信通知用户
        try {
            String time = TimeHelper.getFormatedTime();
            smsService.sendSms(relations.get(0).getGInfoId().getTUserInfo().getTelphone(), "{\"name\":\"" + relations.get(0).getUgInfoId().getTUserInfo().getName() + "\", \"time\":\"" + time + "\"}", "SMS_117517537");
        } catch (Exception e) {
            LOG.error(e.toString());
        }
        return gsonStr(error);

    }

    @POST
    @Path("/drug")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String alertOldsToEatDrug(Introduction introduction) {
        Map<String, Object> map = new HashMap<>();
        TUserGuardianInfo guardian;
        TUserUnderGuardiansInfo underGuardians;
        TUserInfo userInfo;
        Integer g;
        Integer ug;
        //取出参数
        try {
            g = Integer.parseInt(introduction.getSendUid());
            ug = Integer.parseInt(introduction.getReceiveUid());
        } catch (Exception e) {
            return gsonStr(Error.TypeError);
        }
        //检查关系是否存在
        boolean hasRelation = relationService.checkRelation(g, ug);
        if (!hasRelation)
            return gsonStr(Error.Unkonwn);
        //查找被监护人的设备id
        userInfo = userInfoService.findById(ug);
        String device_id = userInfo.getDeviceId();
        //发送吃药的请求
        Error e = pushService.PushTimeToEatMedicines(introduction, device_id);
        return gsonStr(e);

    }


    /**
     * 转发任意的消息体到指定到手机
     *
     * @param json
     * @return
     */
    @POST
    @Path("/custom")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String pushAnyMessage(String json) {
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        Integer from;
        Integer to;
        String message;
        TUserInfo fromUser, toUser;

        try {
            from = Integer.parseInt("" + map.get("from"));
            to = Integer.parseInt("" + map.get("to"));
            if (from.equals("null") || to.equals("null"))
                return gsonStr(Error.NotFond);
            message = (String) map.get("message");
            fromUser = userInfoService.findById(from);
            toUser = userInfoService.findById(to);
            if (fromUser == null || toUser == null)
                return gsonStr(Error.NotFond);
            LOG.info("用户ID" + from + "尝试给用户ID" + to + "发送一条自定义信息，内容为：" + message);
            Error error = pushService.PushCustomMessage(message, toUser.getDeviceId());
            return gsonStr(error);
        } catch (Exception e) {
            LOG.error("发送自定义信息异常");
            e.printStackTrace();
            return gsonStr(Error.Unkonwn);
        }

    }


    @POST
    @Path("/allusers")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String pushAnyMessageToAllUsers(String json) {
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        Integer from;
        Integer to;
        String message;
        TUserInfo fromUser, toUser;
        List<String> toList = new ArrayList<>();
        List<Error> errors = new ArrayList<>();

        try {
            from = Integer.parseInt("" + map.get("from"));

            if (map.get("to") != null) {

                JSONArray textArray = JSONArray.fromObject((String) map.get("to"));
                Iterator iterator = textArray.iterator();
                while (iterator.hasNext()) {
                    JSONObject text = (JSONObject) iterator.next();
                    toList.add(text.getString("user"));
                }
            }
            if (from.equals("null") || toList.size() == 0)
                return gsonStr(Error.NotFond);
            message = (String) map.get("message");
            fromUser = userInfoService.findById(from);
            for (String userid : toList) {
                int toid = Integer.parseInt(userid);
                toUser = userInfoService.findById(toid);
                if (fromUser == null || toUser == null) {
                    errors.add(Error.NotFond);
                    continue;
                }
                LOG.info("用户ID" + from + "尝试给用户ID" + toid + "发送一条自定义信息，内容为：" + message);
                Error error = pushService.PushCustomMessage(message, toUser.getDeviceId());
                errors.add(error);
            }
            return gsonObj(Error.Success, errors);
        } catch (Exception e) {
            LOG.error("发送自定义信息异常");
            e.printStackTrace();
            return gsonStr(Error.Unkonwn);
        }
    }

    @POST
    @Path("/emergency")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String pushEmergencyMessage(String json) {
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        Integer from;
        Integer to;
        String message;
        TUserInfo fromUser, toUser;
        List<String> toList = new ArrayList<>();
        List<Error> errors = new ArrayList<>();

        try {
            from = Integer.parseInt("" + map.get("from"));
            message = (String) map.get("message");
            fromUser = userInfoService.findById(from);
            Map fieldMap = new HashedMap();
            fieldMap.put("ug_info_id", from);
            List<TUserRelation> gids = relationService.findAllByField(fieldMap);
            for (TUserRelation relation : gids) {
                toUser = relation.getGInfoId().getTUserInfo();
                if (fromUser == null || toUser == null) {
                    errors.add(Error.NotFond);
                    continue;
                }
                LOG.info("用户ID" + from + "尝试给用户ID" + toUser.getUId() + "发送一条自定义信息，内容为：" + message);
                Error error = pushService.PushCustomMessage(message, toUser.getDeviceId());
                toList = new ArrayList<>();
                toList.add(toUser.getDeviceId());
                pushService.PushEmergency(toList, fromUser.getName());
                errors.add(error);
            }
            return gsonObj(Error.Success, errors);
        } catch (Exception e) {
            LOG.error("发送自定义信息异常");
            e.printStackTrace();
            return gsonStr(Error.Unkonwn);
        }
    }


    private String gsonStr(Error error) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
    }

    private String gsonObj(Error error, Object object) {
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning(), object));
    }

}
